package ru.ifmo.swing.genetics.config.common;

import org.uncommons.watchmaker.swing.EvolutionControl;
import ru.ifmo.swing.Panel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;

/**
 * @author avhaliullin
 */
public class MultiChooser<T> extends ru.ifmo.swing.Panel {
    private final Panel control;
    private final Set<ChooserListener<List<T>>> listeners = new HashSet<ChooserListener<List<T>>>();
    private JTabbedPane itemControl;
    private final Map<String, T> options;
    private final List<JCheckBox> checkBoxes = new ArrayList<JCheckBox>();

    public MultiChooser(final Map<String, T> options) {
        this.options = options;
        this.control = new Panel();
        control.setHorizontal(false);
        itemControl = new JTabbedPane();
        control.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        List<String> optsList = new ArrayList<String>(options.keySet());
        Collections.sort(optsList);

        for (String opt : optsList) {
            JCheckBox checkBox = new JCheckBox(opt);
            control.add(checkBox);
            checkBox.setSelected(true);
            checkBoxes.add(checkBox);
            checkBox.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    handleItems();
                }
            });

            T item = options.get(opt);
            if (item instanceof EvolutionControl) {
                itemControl.addTab(opt, ((EvolutionControl) item).getControl());
            }
        }

        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
        add(control);
        add(Box.createHorizontalStrut(10));
        add(itemControl);
        handleItems();
    }

    public List<T> getItems() {
        List<T> enabledList = new ArrayList<T>();
        for (JCheckBox box : checkBoxes) {
            T item = options.get(box.getText());
            if (box.isSelected()) {
                enabledList.add(item);
            }
        }
        return enabledList;
    }

    private void handleItems() {
        List<T> enabledList = getItems();
        for (ChooserListener<List<T>> listener : listeners) {
            listener.chosen(enabledList);
        }
    }

    public void addListener(ChooserListener<List<T>> listener) {
        listeners.add(listener);
        listener.chosen(getItems());
    }

    public void removeListener(ChooserListener<List<T>> listener) {
        listeners.remove(listener);
    }

    public void reset() {
    }

}
